<template>
  <div v-if="editOpen">
    <t-table :selected-row-keys="selectedRowKeys" @select-change="(val) => { selectedRowKeys = val }" rowKey="id"
      :data="data" :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #applyDate="{ row, rowIndex }">
        <t-date-picker clearable :status="row.applyDateStatus"
          @change="(val) => { if (row.applyDate !== '') { row.applyDateStatus = 'default' } }" v-model="row.applyDate">
          <div slot="tips" v-if="row.applyDateStatus === 'error'">不能为空</div>
        </t-date-picker>
      </template>
      <template #useCompany="{ row, rowIndex }">
        <t-tree-select :status="row.useCompanyStatus"
          @change="(val, content) => { row.useCompanyId = content.node.data.id; if (row.useCompany !== '') { row.useCompanyStatus = 'default' } }"
          v-if="row.isInnerCompany === '1'" style="width:390px" clearable filterable
          :treeProps="{ keys: { value: 'label' } }" v-model="row.useCompany" :data="deptMenuOptions" placeholder="选择单位">
          <div slot="tips" v-if="row.useCompanyStatus === 'error'">不能为空</div>
          <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
          <template #label>
            <t-switch size="medium" v-model="row.isInnerCompany" :label="['内部', '外部']" :customValue="['1', '0']"
              @change="() => { row.useCompany = ''; row.useCompanyId = null; row.useCompanyStatus = 'default' }"></t-switch>
          </template>
        </t-tree-select>
        <t-select v-else v-model="row.useCompany" creatable filterable placeholder="请输入" :status="row.useCompanyStatus"
          @change="(val, content) => { row.useCompanyId = content.option?.id; if (row.useCompany !== '') { row.useCompanyStatus = 'default' } }"
          :loading="companyLoading" @search="remoteCompanyMethod" :options="companyOptions"
          @create="createCompanyOptions" style="width: 390px;display: inline-block">
          <div slot="tips" v-if="row.useCompanyStatus === 'error'">不能为空</div>
          <div slot="tips" v-else>搜索不到请切换外部单位后手输</div>
          <template #label>
            <t-switch size="medium" v-model="row.isInnerCompany" :label="['内部', '外部']" :customValue="['1', '0']"
              @change="() => { row.useCompany = ''; row.useCompanyId = null; row.useCompanyStatus = 'default' }"></t-switch>
          </template>
        </t-select>
      </template>
      <template #linker="{ row, rowIndex }">
        <t-input :status="row.linkerStatus"
          @change="(val) => { if (row.linker !== '') { row.linkerStatus = 'default' } }" clearable v-model="row.linker">
          <div slot="tips" v-if="row.linkerStatus === 'error'">不能为空</div>
        </t-input>
      </template>
      <template #linkerPhone="{ row, rowIndex }">
        <t-input :status="row.linkerPhoneStatus"
          @change="(val) => { if (row.linkerPhone !== '') { row.linkerPhoneStatus = 'default' } }" clearable
          v-model="row.linkerPhone">
          <div slot="tips" v-if="row.linkerPhoneStatus === 'error'">不能为空</div>
        </t-input>
      </template>
      <template #efficiency="{ row, rowIndex }">
        <t-input-adornment append="万元">
          <t-input-number :decimal-places="2"
            @keyup="() => { if (row.efficiency) { row.efficiency = Number((row.efficiency || 0).toString().match(/^\d+(?:\.\d{0,2})?/)) } }"
            :allowInputOverLimit="false" clearable v-model="row.efficiency" theme="normal" :min="0"></t-input-number>
        </t-input-adornment>
      </template>
      <template #opinion="{ row, rowIndex }">
        <t-textarea :status="row.opinionStatus"
          @change="(val) => { if (row.opinion !== '') { row.opinionStatus = 'default' } }" :autosize="{ minRows: 5 }"
          v-model="row.opinion" placeholder="请输入内容">
          <div slot="tips" v-if="row.opinionStatus === 'error'">不能为空</div>
        </t-textarea>
      </template>
      <template #op="{ row, rowIndex }">
        <file-upload :status="row.imageStatus" v-model="row.sysAttMainVo.sysAttMainIds"
          :fileList.sync="row.sysAttMainEntities" :multiple="true" tips="">
          <t-button variant="outline">
            <t-icon name="cloud-upload" slot="icon" />
            点击上传
          </t-button>
          <div slot="tips" v-if="row.imageStatus === 'error'">不能为空</div>
        </file-upload>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table rowKey="id" size="small" :data="data" :columns="columns2">
      <template #index="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #efficiency="{ row }">
        {{ row.efficiency }}万元
      </template>
      <template #op="{ row }">
        <div v-if="row?.sysAttMainEntities?.length > 0">
          <a class="t-button-link" target="_blank" v-for="(item, index) in row.sysAttMainEntities"
            :href="item.fullFilePath" :key="index">
            {{ item.name }}
          </a>
        </div>
      </template>
    </t-table>
  </div>
</template>

<script lang="jsx">
import FileUpload from "@/components/FileUpload/index.vue"

export default {
  name: "evaluate-list",
  components: {
    FileUpload
  },
  props: {
    value: Array,
    editOpen: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      companyOptions: [],
      companyLoading: false,
      selectedRowKeys: [],
      deptMenuOptions: [],
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64,
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'applyDate',
          // title: "应用时间",
          align: "center",
          width: 210,
          title: (h, { colIndex }) => <div><span style="color: red;margin-right: 3px;">*</span>应用时间</div>,
        },
        {
          colKey: 'useCompany',
          // title: "应用单位",
          align: "center",
          width: 420,
          title: (h, { colIndex }) => <div><span style="color: red;margin-right: 3px;">*</span>应用单位</div>,
        },
        {
          colKey: 'linker',
          // title: "应用联系人",
          align: "center",
          title: (h, { colIndex }) => <div><span style="color: red;margin-right: 3px;">*</span>应用联系人</div>,
          width: 200,
        },
        {
          colKey: 'linkerPhone',
          // title: "应用联系手机号",
          align: "center",
          title: (h, { colIndex }) => <div><span style="color: red;margin-right: 3px;">*</span>应用联系手机号</div>,
          width: 200,
        },
        {
          colKey: 'efficiency',
          // title: "经济效益",
          align: "center",
          width: 200,
          title: (h, { colIndex }) => <div><span style="color: red;margin-right: 3px;">*</span>经济效益</div>,
        },
        {
          colKey: 'opinion',
          // title: "评价意见",
          align: "center",
          title: (h, { colIndex }) => <div><span style="color: red;margin-right: 3px;">*</span>评价意见</div>,
          width: 200,
        },
        {
          colKey: 'op',
          title: "附件",
          align: "center",
          width: 200,
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'applyDate',
          title: "应用时间",
          align: "center",
        },
        {
          colKey: 'useCompany',
          title: "应用单位",
          align: "center",
        },
        {
          colKey: 'linker',
          title: "应用联系人",
          align: "center",
        },
        {
          colKey: 'linkerPhone',
          title: "应用联系手机号",
          align: "center",
        },
        {
          colKey: 'efficiency',
          title: "经济效益",
          align: "center",
        },
        {
          colKey: 'opinion',
          title: "评价意见",
          align: "center",
        },
        {
          colKey: 'op',
          title: "附件",
          align: "center",
        },
      ],
    }
  },
  watch: {
    data: {
      handler (val, old) {
        const newData = this.data.map((d, index) => ({ ...d, sort: index + 1 }))
        this.$emit("input", newData);
      },
      immediate: true,
      deep: true,
    },
    value: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val && val.length > 0) {
          let newArr = val.map(data => {
            return {
              ...data,
              initType: 'init',
              sysAttMainVo: {
                sysAttMainIds: data?.sysAttMainVo?.sysAttMainIds || []
              },
              sysAttMainEntities: data.sysAttMainEntities?.map(val => {
                return {
                  ...val, name: val.fileName, url: val.fullFilePath,
                  fullFilePath: val.fullFilePath, id: val.id, filePath: val.filePath
                }
              }),
            }
          })
          // 防止无限循环，简单比较一下
          if (JSON.stringify(val) !== JSON.stringify(this.data)) {
            this.data = newArr
          }
        }
      }
    },

  },
  created () {
    this.getDeptTreeSelect(this.$store.state.user.deptId)
  },
  methods: {
    getDeptTreeSelect (id) {
      return this.$api.system.dept.treeSelectAllIn().then(response => {
        this.deptMenuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    createCompanyOptions (value) {
      this.companyOptions.push({
        label: `${value}`,
        value,
      });
    },
    remoteCompanyMethod (search) {
      this.companyLoading = true;
      this.$api.system.dept.selectAllOutDeptList({ deptName: search }).then(response => {
        this.companyOptions = response.data.map(val => ({
          ...val,
          label: `${val.deptName}`,
          value: val.deptName,
        }));
        this.companyLoading = false;
      }).catch((e) => {
        this.companyLoading = false;
        this.$message.error(e.toString());
      });
    },
    onUploadChange (value, context, row) {
      this.$nextTick(() => {
        if (row.sysAttMainVo?.sysAttMainIds?.length > 0) {
          row.imageStatus = 'default'
        }
      })
    },
    checkData () {
      const title = "评价列表"
      // 非空判断
      const isValidate = this.data.every((val, index) => {
        // if ((val.sysAttMainVo?.sysAttMainIds && val.sysAttMainVo?.sysAttMainIds?.length <= 0) || !val.sysAttMainVo?.sysAttMainIds) {
        //   this.$set(this.data[index], 'imageStatus', 'error')
        //   this.$message.error(`${title}：第${index + 1}条"图片"不能为空`);
        //   return false;
        // }
        // this.$set(this.data[index], 'imageStatus', 'default')

        if (!val.applyDate) {
          this.$set(this.data[index], 'applyDateStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"应用时间"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'applyDateStatus', 'default')

        if (!val.useCompany) {
          this.$set(this.data[index], 'useCompanyStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"应用单位"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'useCompanyStatus', 'default')

        if (!val.linker) {
          this.$set(this.data[index], 'linkerStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"应用联系人"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'linkerStatus', 'default')

        if (!val.linkerPhone) {
          this.$set(this.data[index], 'linkerPhoneStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"应用联系手机号"不能为空`);
          return false;
        }
        const phoneRight = val.linkerPhone.match(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/);
        if (!phoneRight) {
          this.$set(this.data[index], 'linkerPhoneStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"应用联系手机号格式错误"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'linkerPhoneStatus', 'default')

        if (!val.opinion) {
          this.$set(this.data[index], 'opinionStatus', 'error')
          this.$message.error(`${title}：第${index + 1}条"评价意见"不能为空`);
          return false;
        }
        this.$set(this.data[index], 'opinionStatus', 'default')
        return true;
      })
      return isValidate;
    },
    addData () {
      this.data.push({
        id: Date.parse(new Date()),
        sysAttMainVo: {
          sysAttMainIds: [],
        },
        applyDate: '',
        useCompany: '',
        useCompanyId: null,
        linker: '',
        linkerPhone: '',
        efficiency: 0,
        isInnerCompany: '1'
      })
    },
    upData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData () {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray (arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
  }
}
</script>

<style lang="less" scoped>
/deep/ .t-upload__single-display-text {
  justify-content: center;
}
</style>
